import React from "react";
import { Result } from "antd";
import { useUser } from "../../contexts/UserContext";

interface PermissionGuardProps {
  permission: string;
  children: React.ReactNode;
  fallback?: React.ReactNode;
}

const PermissionGuard: React.FC<PermissionGuardProps> = ({
  permission,
  children,
  fallback,
}) => {
  const { user, hasPermission } = useUser();

  if (!user) {
    return fallback ? (
      <>{fallback}</>
    ) : (
      <Result status="403" title="403" subTitle="请先登录" />
    );
  }

  if (!hasPermission(permission)) {
    return fallback ? (
      <>{fallback}</>
    ) : (
      <Result status="403" title="403" subTitle="抱歉，您没有权限访问此页面" />
    );
  }

  return <>{children}</>;
};

export default PermissionGuard;
